﻿// News Framework
// (C) Tanzim Saqib. Oct 25, 2010.
// http://TanzimSaqib.com | http://newsfx.codeplex.com

namespace TanzimSaqib.NewsFramework
{
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;
    using System;
    using System.Windows;
    using Microsoft.Phone.Tasks;

    public class RssViewModel : ViewModelBase
    {
        #region Properties

        private ApplicationBarIconButton _Delete = new ApplicationBarIconButton(new Uri("/Images/appbar.delete.rest.png", UriKind.Relative));
        private ApplicationBarIconButton _Save = new ApplicationBarIconButton(new Uri("/Images/appbar.save.rest.png", UriKind.Relative));
        private ApplicationBarIconButton _ZoomOut = new ApplicationBarIconButton(new Uri("/Images/appbar.minus.rest.png", UriKind.Relative));
        private ApplicationBarIconButton _ZoomIn = new ApplicationBarIconButton(new Uri("/Images/appbar.new.rest.png", UriKind.Relative));
        private ApplicationBarIconButton _GoToOriginalSite = new ApplicationBarIconButton(new Uri("/Images/appbar.next.rest.png", UriKind.Relative));
        private ApplicationBarMenuItem _ShareViaEmail = new ApplicationBarMenuItem("share via email");
        private ApplicationBarMenuItem _ShareViaSMS = new ApplicationBarMenuItem("share via sms");

        private RssItem _SelectedRssItem;
        private string _SelectedFeed = string.Empty;
        private string _SelectedItem = string.Empty;
        private int _CurrentFontSize = 14;
        private string _Content = string.Empty;

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        private WebBrowser Browser { get; set; }
        private IApplicationBar AppBar { get; set; }

        private Visibility _LoadingTextVisibility;
        public Visibility LoadingTextVisibility
        {
            get { return _LoadingTextVisibility; }

            private set
            {
                _LoadingTextVisibility = value;
                RaisePropertyChanged("LoadingTextVisibility");
            }
        }
        
        #endregion

        public RssViewModel()
        {
            if (!IsDataLoaded)
            {
                if (!Fx.IsDesignMode)
                {
                    BackgroundImageSource = PhoneUI.GetBackgroundBrush();
                    LoadingTextVisibility = Visibility.Visible;
                }
            }

            IsDataLoaded = false;
        }

        #region Methods

        private void PrepareApplicationBar()
        {
            AddApplicationBar();
            AppBar.Buttons.Add(FeedData.RSSItems.ContainsKey(_SelectedRssItem.Link) ? _Delete : _Save);
            AppBar.Buttons.Add(_ZoomOut);
            AppBar.Buttons.Add(_ZoomIn);
            AppBar.Buttons.Add(_GoToOriginalSite);
            AppBar.MenuItems.Add(_ShareViaEmail);
            AppBar.MenuItems.Add(_ShareViaSMS);
            SetSaveOrDeleteButton();
            AppBar.IsVisible = true;
        }

        private void SetSaveOrDeleteButton()
        {
            AppBar.Buttons[0] = FeedData.RSSItems.ContainsKey(_SelectedRssItem.Link) ? _Delete : _Save;
        }

        private void AddApplicationBar()
        {
            _Delete.Text = "delete";
            _Delete.Click += _Delete_Click;

            _Save.Text = "save";
            _Save.Click += _Save_Click;

            _ZoomOut.Text = "zoom-out";
            _ZoomOut.Click += _ZoomOut_Click;

            _ZoomIn.Text = "zoom-in";
            _ZoomIn.Click += _ZoomIn_Click;

            _GoToOriginalSite.Text = "original";
            _GoToOriginalSite.Click += gotToOriginalSite_Click;

            _ShareViaEmail.Click += _ShareViaEmail_Click;
            _ShareViaSMS.Click += _ShareViaSMS_Click;
        }

        private void RenderPage()
        {
            var html = FxConstants.ArticleViewTemplate
                .Replace("{article-header}", _SelectedRssItem.Title)
                .Replace("{article-content}", _Content)
                .Replace("{background-specific-style}",
                         PhoneUI.CurrentPhoneBackground == PhoneBackground.Dark
                             ? Fx.Instance.Settings["Article-View-DarkBackground-CSS"]
                             : Fx.Instance.Settings["Article-View-LightBackground-CSS"])
                .Replace("{common-style}", Fx.Instance.Settings["Article-View-CSS"]);

            Browser.NavigateToString(html);
        }

        #endregion

        #region Event handlers

        void _ShareViaSMS_Click(object sender, EventArgs e)
        {
            new SmsComposeTask()
            {
                Body =
                    Fx.Instance.Settings["ShareArticleBodyTemplate"]
                    .Replace("{article-title}", _SelectedRssItem.Title)
                    .Replace("{article-url}", _SelectedRssItem.Link)
            }.Show();
        }

        void _ShareViaEmail_Click(object sender, EventArgs e)
        {
            new EmailComposeTask()
            {
                Subject = Fx.Instance.Settings["ShareArticleSubjectTemplate"],
                Body =
                    Fx.Instance.Settings["ShareArticleBodyTemplate"]
                    .Replace("{article-title}", _SelectedRssItem.Title)
                    .Replace("{article-url}", _SelectedRssItem.Link)
            }.Show();
        }

        void _Delete_Click(object sender, EventArgs e)
        {
            FeedData.DeleteRssItem(_SelectedRssItem);
            SetSaveOrDeleteButton();
        }

        void _Save_Click(object sender, EventArgs e)
        {
            FeedData.SaveRssItem(_SelectedRssItem);
            SetSaveOrDeleteButton();
        }

        void _ZoomOut_Click(object sender, EventArgs e)
        {
            if(_CurrentFontSize > 6)
            {
                _CurrentFontSize -= 2;
                Browser.InvokeScript("setContent", _CurrentFontSize.ToString(), _SelectedRssItem.Title, _Content);   
            }
        }

        void _ZoomIn_Click(object sender, EventArgs e)
        {
            if (_CurrentFontSize < 36)
            {
                _CurrentFontSize += 2;
                Browser.InvokeScript("setContent", _CurrentFontSize.ToString(), _SelectedRssItem.Title, _Content);
            }
        }

        void gotToOriginalSite_Click(object sender, EventArgs e)
        {
            var browserTask = new WebBrowserTask();
            browserTask.URL = _SelectedRssItem.Link;
            browserTask.Show();
        }

        public void browser_Loaded(CommandArgs args)
        {
            Browser = args.Source as WebBrowser;
            Browser.Navigated += Browser_Navigated;
        }

        void Browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            Browser.Visibility = Visibility.Visible;
            LoadingTextVisibility = Visibility.Collapsed;
            PrepareApplicationBar();
        }

        public void RssView_Loaded(CommandArgs args)
        {
            var navContext = Fx.Instance.RootPage.NavigationContext;

            if (navContext.QueryString.TryGetValue("feed", out _SelectedFeed) && navContext.QueryString.TryGetValue("item", out _SelectedItem))
            {
                var feed = FeedData.Feeds[_SelectedFeed];
                _SelectedRssItem = feed.Items[int.Parse(_SelectedItem)];
            }
            else if (navContext.QueryString.TryGetValue("latest", out _SelectedFeed))
            {
                _SelectedRssItem = FeedData.Feeds[Fx.Instance.Feeds.Main].Items[int.Parse(_SelectedFeed)];
            }
            else if (navContext.QueryString.TryGetValue("saved", out _SelectedFeed))
            {
                _SelectedRssItem = FeedData.RSSItems[_SelectedFeed];
            }

            var page = args.Source as PhoneApplicationPage;
            AppBar = page.ApplicationBar;

            Check.Null(_SelectedRssItem);
            _Content = _SelectedRssItem.Content;
            RenderPage();
        }

        #endregion
    }
}
